package cn.itcast.bassm.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.itcast.bassm.mapper.UserMapper;
import cn.itcast.bassm.pojo.BaseButton;
import cn.itcast.bassm.pojo.ClickButton;
import cn.itcast.bassm.pojo.ComplexButton;
import cn.itcast.bassm.pojo.Menu;
import cn.itcast.bassm.pojo.PublicandNumber;
import cn.itcast.bassm.pojo.Returnxx;
import cn.itcast.bassm.pojo.Unitdoor;
import cn.itcast.bassm.pojo.Uploadfile;
import cn.itcast.bassm.pojo.ViewButton;
import cn.itcast.bassm.pojo.Wx_access_token;
import cn.itcast.bassm.pojo.resupels;
import cn.itcast.bassm.service.CoreService;
import cn.itcast.bassm.service.UserService;
import cn.itcast.bassm.util.MenuUtil;
import cn.itcast.bassm.util.SignUtil;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

@Controller
@RequestMapping("/weixingzh")
public class WeiXinGongZhongHaoCntroller {
	
		@Autowired 
		private UserService userService;
		
		@Autowired 
		private UserMapper  userMapper;
	  
	    /** 
	     * 确认请求来自微信服务器 
	     */
		
		@RequestMapping(value="/doGet", method=RequestMethod.GET)
	    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
	        // 微信加密签名  
	        String signature = request.getParameter("signature");  
	        // 时间戳  
	        String timestamp = request.getParameter("timestamp");  
	        // 随机数  
	        String nonce = request.getParameter("nonce");  
	        // 随机字符串  
	        String echostr = request.getParameter("echostr");  
	  
	        PrintWriter out = response.getWriter();  
	        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败  
	        if (SignUtil.checkSignature(signature, timestamp, nonce)) {  
	            out.print(echostr);  
	        }  
	        out.close();  
	        out = null;  
	    }  
	  
	    /** 
	     * 处理微信服务器发来的消息 
	     */
		
		@RequestMapping(value="/doGet",method=RequestMethod.POST)
	    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
	       
			// 将请求、响应的编码均设置为UTF-8（防止中文乱码）  
	        request.setCharacterEncoding("UTF-8");  
	        response.setCharacterEncoding("UTF-8");
	  
	        // 微信加密签名  
	        String signature = request.getParameter("signature");  
	        // 时间戳  
	        String timestamp = request.getParameter("timestamp");  
	        // 随机数  
	        String nonce = request.getParameter("nonce"); 
	        // 响应消息  
	        PrintWriter out = response.getWriter();  
	        //验证身份 如果成功就处理
	        if (SignUtil.checkSignature(signature, timestamp, nonce)) {  
	            //消息处理
	        	String respXML = userService.processRequest(request);
	        	out.write(respXML);
	        } 
	        
	        out.close();  
	    }
		
		/**
		 * 测试dom4j解析xml
		 * @throws Exception 
		 *//*
		@RequestMapping(value="/dom4j",method=RequestMethod.GET)
	    public void dodom4j(HttpServletRequest request, HttpServletResponse response) throws Exception {  
		// 通过IO获得Document
		SAXReader reader = new SAXReader();
		Document doc = reader.read(new File("E:\\桌面\\1201\\ssm\\src\\test.xml"));
		
		//得到根节点
		Element root=doc.getRootElement();
		AnalysisXML.recursiveParseXML(root);
		}*/
		
		
		/**
		 * 获取access_token
		 */
		@ResponseBody
		@RequestMapping(value="/accessandtoken",method=RequestMethod.GET)
		public String  accessandtoken(){
			String id="3";
			String uid="wx75a2607f7425fe6e&secret=55ff660fa63dbaa8fb63d25ae8a9ba99";
			Wx_access_token wx=userMapper.selectandwx_access_token(id);
			if(wx==null){//先查询accessandtoken存在不存在
				//创建accessToken去微信接口中获取
				String jsontow= seledoBasicuseracctionto();
	            JsonParser parser2 = new JsonParser(); // 创建JSON解析器
	            JsonObject object2 = (JsonObject) parser2.parse(jsontow); // 创建JsonObject对象
	            String accesstoken=object2.get("access_token").getAsString();
	            String expiresin=object2.get("expires_in").getAsString();
	            Long createtime=System.currentTimeMillis();
	            String userid=uid;
	            Date data=new Date();
    	        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	        String createdate = dateFormat.format(data);
                userMapper.intsetandwx_access_token(createtime,userid,createdate,accesstoken,expiresin);//更新数据库
                Map<String, Object>map = new HashMap<String, Object>();
    			map.put("result", "1");
    			map.put("accesstoken", accesstoken);
    			JSONObject json2=JSONObject.fromObject(map);
    			return json2.toString(); 
			}else {//不为空的时候
	                String expires_in = String.valueOf(wx.getExpiresin());  
	                String create_time = String.valueOf(wx.getCreatetime()); 
	                int _in = Integer.parseInt(expires_in);  
	                long _time = Long.parseLong(create_time); 
				if ((System.currentTimeMillis()-_time)/1000 < _in) {//还有效
					String json = wx.getAccesstoken();
					Map<String, Object>map = new HashMap<String, Object>();
					map.put("result", "1");
					map.put("accesstoken", json);
					JSONObject json2=JSONObject.fromObject(map);
					return json2.toString(); 
				}else {
					//已经失效了
					String jsontow= seledoBasicuseracctionto();//请求获取access_token
		            JsonParser parser2 = new JsonParser(); // 创建JSON解析器
		            JsonObject object2 = (JsonObject) parser2.parse(jsontow); // 创建JsonObject对象
		            String accesstoken=object2.get("access_token").getAsString();
		            String expiresin2=object2.get("expires_in").getAsString();

		            Long createtime=System.currentTimeMillis();
	                Date data=new Date();
	    	        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    	        String createdate = dateFormat.format(data);

	                userMapper.upandwx_access_token(createtime,createdate,accesstoken,expiresin2,id);//更新数据库
	                Map<String, Object>map = new HashMap<String, Object>();
	    			map.put("result", "1");
	    			map.put("accesstoken", accesstoken);
	    			JSONObject json2=JSONObject.fromObject(map);
	    			return json2.toString(); 
				}
			}
		}
		
		
		
		/**
		 * 创建菜单
		 * @param cardnumber
		 * @param model
		 * @return
		 */
		@ResponseBody
		@RequestMapping(value="/chuanjiancaidan",produces = "text/html;charset=UTF-8",method=RequestMethod.GET)
		public String chuanjiancaidan(){	
			String msg= null;
			ClickButton btn11 = new ClickButton();
			btn11.setName("绑定用户");
			btn11.setType("click");
			btn11.setKey("KEY_WEATHER");
			
			
			/*ViewButton btn21 = new ViewButton();
			btn21.setName("门禁安装视频");
			btn21.setType("view");
			btn21.setUrl("http://m.youku.com/video/id_XMzE0NTI3MDQ5Mg==.html?refer=pc-sns-1&source=");
			
			
			ViewButton btn22 = new ViewButton();
			btn22.setName("门禁安装文档");
			btn22.setType("view");
			btn22.setUrl("https://wk.baidu.com/view/a0acabb9988fcc22bcd126fff705cc1755275fb0?pcf=2&fqr=1");
			
			ComplexButton btn2 = new ComplexButton();
			btn2.setName("相关讲解");
			btn2.setSub_button(new BaseButton[]{btn21,btn22});*/
			ClickButton btn12 = new ClickButton();
			btn12.setName("家庭注册");
			btn12.setType("click");
			btn12.setKey("KEY_HOMEUSER");
			
			ClickButton btn13 = new ClickButton();
			btn13.setName("彩之云下载");
			btn13.setType("click");
			btn13.setKey("KEY_CAIZHIYUNDOWN");
			
			
			//菜单对象
			Menu menu = new Menu();
			menu.setButton(new BaseButton[]{btn11,btn12,btn13});
			
			//转换成JSON
			String json=JSONObject.fromObject(menu).toString();
			
			String accessToken=DeledoBasicuser();
			boolean en = MenuUtil.createMenu(json, accessToken);
			if(en){
				System.out.println("创建好了");
				msg="创建好了";
			}else {
				System.out.println("失败了");
				msg="失败了";
			}
			
			return msg;
		}
		
		/**
		 * 用户选择小区地址
		 */
		@RequestMapping(value="/Selectionofcommunity",method=RequestMethod.GET)
		public String Selectionofcommunity(String openid,String cardnumber,Model model){
			String openidto=openid;
			PublicandNumber pu = userMapper.selectPublicandNumberandcardnumber(openidto);
			String  bangding= pu.getBinding();
			if(bangding.equals("0")){//没有绑定
				List<Uploadfile>listandUploadfile = userMapper.selectFinuserandCardnumbertwoGo(cardnumber);
				if(listandUploadfile.size()==0){//数据中有没有对应的数据
					return "khbcz";
				}else {
					model.addAttribute("listandUploadfile",listandUploadfile);
					model.addAttribute("openid",openid);
					model.addAttribute("cardnumber",cardnumber);
				}
				return "xzym";
			}else {//已经绑定了
				return "yjbd";		
			}
		}
		
		
		/**
		 * 根据卡号判断用户是否在PAD那边上传成功
		 * @param cardnumber
		 * @param model
		 * @return
		 * @throws UnsupportedEncodingException 
		 */
		
		@RequestMapping(value="/selectFinuserandCardnumber",method=RequestMethod.GET)
		public String selectFinuserandCardnumber(String openid,String cardnumber,String yaddressto,Model model) throws UnsupportedEncodingException{
			String str=yaddressto;
			String binding="1";
			byte[] bytes;
			bytes = str.getBytes("ISO-8859-1");
			String yaddress=new String(bytes,"utf-8");
			
			//根据用户的选择的小区地址和卡号，来查询是否已经存在绑定了
			List<PublicandNumber>listpublicandNumber = userMapper.selectFinuserandCardnumberandPublicandNumber(cardnumber,yaddress,binding);
			
			if(listpublicandNumber.size()==0){ //用户选择的小区和卡号，没有存在已经绑定的用户
				
				
				//根据卡号和小区地址查询用户信息
				List<Uploadfile>listuploadfile = userMapper.selectFinuserandCardnumber(cardnumber,yaddress);
				
				if(listuploadfile.size()==0){
					return "sjwsc";
				}else {
					//用户信息已经上传
					List<Unitdoor>unitdoor=userMapper.YaddressandSelectUnitdoor(yaddress);
					int id = listuploadfile.get(0).getYid();
					String yid = String.valueOf(id);
					String yfilename=listuploadfile.get(0).getYfilename();
					model.addAttribute("unitdoor",unitdoor);
					model.addAttribute("yid",yid);
					model.addAttribute("yfilename",yfilename);
					model.addAttribute("yaddress",yaddress);
					model.addAttribute("cardnumber",cardnumber);
					model.addAttribute("openid",openid);
					return "gzhbd";
				}
				
			}else {
				//已经存在卡号和小区相同的用户，已经被绑定了
				return "yhysy";
			}
			
			
			
			
		}
		
		
		/**
		 * 微信绑定用户
		 * @param id
		 * @return
		 * @throws Throwable
		 */
		@RequestMapping(value="/addUserweixin",method=RequestMethod.POST)
		@ResponseBody
		public Returnxx addUserInformationFist(String yid,String address,String dong,String nickname,String moblie,String ysex,String openid ) throws Throwable{
				Returnxx rb = new Returnxx();
				Calendar curr = Calendar.getInstance();
				curr.set(Calendar.YEAR,curr.get(Calendar.YEAR)+1);
	          	Date date2=curr.getTime();  
	          	SimpleDateFormat sdf3 = new SimpleDateFormat("yyyyMMdd");  
	          	String validTo2= sdf3.format(date2);
	          	
	          	
	          	Date data3=new Date();
	            SimpleDateFormat dateFormat3=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	            String updatetime = dateFormat3.format(data3);
	          	
	          	
				String yowner="业主";

				String yindex="1";
				String examine="1";
				String idnumber=validTo2;
				String yaddress=address;
				String binding="1";
				
				try {
					
					//更新用户信息
					userMapper.UpweixinandUser(yid, address, dong, nickname, moblie, yowner, ysex, updatetime, yindex, examine, idnumber);
					System.out.println(openid+"------"+yaddress+"--------"+binding);
					
					//更新用户在PublicandNumber填充标识
					userMapper.UpPublicandNumberandbangding(openid, yaddress, binding,yid);
					
					rb.setMsg("1");
					
				} catch (Exception e) {
					rb.setMsg("2");
					e.printStackTrace();
				}
			
			return rb;
		}

		
		/**
		 * 获取access_token测试
		 */
		@ResponseBody
		@RequestMapping(value="/accessandtoken2",method=RequestMethod.GET)
		public String   accessandtoken2(){
			String accountone=DeledoBasicuser();
            String scene_id="55566600";
            String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="+accountone;
            String jsonStr ="{\"expire_seconds\": 2592000,\"action_name\": \"QR_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": "+scene_id+"}}}";
            String jsontow= doPostJsonone(url,jsonStr);
            JsonParser parser2 = new JsonParser(); // 创建JSON解析器
            JsonObject object2 = (JsonObject) parser2.parse(jsontow); // 创建JsonObject对象
            String ticket=object2.get("ticket").getAsString();
            String urlh=object2.get("url").getAsString();
			System.out.println(ticket+"=================="+urlh);
			Map<String, Object>map = new HashMap<String, Object>();
			map.put("1", ticket);
			map.put("2", urlh);
			new JSONObject();
			JSONObject json2=JSONObject.fromObject(map);
			return json2.toString();  
		}
		
	    /**
	     * 获取access_token
	     */
	    public String DeledoBasicuser() {
	    	String urlStr ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx75a2607f7425fe6e&secret=55ff660fa63dbaa8fb63d25ae8a9ba99";
	        String result = null;
	        String result2 = null;
	        HttpGet httpDelete = new HttpGet(urlStr);
	        //HttpDelete httpDelete = new HttpDelete(urlStr);

	        try {
	           // HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");// 设置字符集-8");
	            @SuppressWarnings("resource")
	            HttpClient httpClient = new DefaultHttpClient();// 获取HttpClient对象
	            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);// 连接超时
	            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);// 请求超时

	            HttpResponse httpResp = httpClient.execute(httpDelete);// 获取HttpResponse实例
	            if (httpResp.getStatusLine().getStatusCode() == 200) {// 判断是够请求成功
	                result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");// 获取返回的数据
	                String json=result;
	    			JsonParser parser = new JsonParser(); // 创建JSON解析器
	                JsonObject object = (JsonObject) parser.parse(json); // 创建JsonObject对象
	                String accountone=object.get("access_token").getAsString();
	                result2 = accountone;
	            } else {
	               
	            }
	        } catch (ConnectTimeoutException e) {
	           
	        } catch (UnsupportedEncodingException e) {
	           ;
	        } catch (IOException e) {
	            
	        } catch (Exception e) {
	            
	        }

	        return result2;
	    }
	    
	    /**
	     * 获取
	     * @param urlStr
	     * @param jsonstr
	     * @return
	     */
	    public  String doPostJsonone(String urlStr, String jsonstr) {
	        String result = null;
	        HttpPost httpPost = new HttpPost(urlStr);

	        try {
	            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
	            // httpPost.setHeader("Content-Type", "application/json");
	            StringEntity se = new StringEntity(jsonstr, "UTF-8");
	            se.setContentType("text/json");
	            httpPost.setEntity(se);
	            @SuppressWarnings("resource")
	            HttpClient httpClient = new DefaultHttpClient();// 获取HttpClient对象
	            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);// 连接超时
	            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);// 请求超时

	            HttpResponse httpResp = httpClient.execute(httpPost);// 获取HttpResponse实例
	            if (httpResp.getStatusLine().getStatusCode() == 200) {// 判断是够请求成功
	                result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");// 获取返回的数据
	            } else {
	                
	            }
	        } catch (ConnectTimeoutException e) {
	           
	        } catch (UnsupportedEncodingException e) {
	        } catch (IOException e) {
	        } catch (Exception e) {
	        }

	        return result;
	    }
	    
	    
	    /**
	     * 获取access_token
	     */
	    public String seledoBasicuseracctionto() {
	    	System.out.println("11111111111111111111");
	    	String urlStr ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx75a2607f7425fe6e&secret=55ff660fa63dbaa8fb63d25ae8a9ba99";
	    	String result = null;
	        HttpGet httpget = new HttpGet(urlStr);
	        System.out.println(urlStr);
	    

	        try {
	        	
	            @SuppressWarnings("resource")
	            HttpClient httpClient = new DefaultHttpClient();// 获取HttpClient对象
	            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);// 连接超时
	            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);// 请求超时
	            HttpResponse httpResp = httpClient.execute(httpget);// 获取HttpResponse实例
	            if (httpResp.getStatusLine().getStatusCode() == 200) {// 判断是够请求成功
	                result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");// 获取返回的数据
	            } else {
	               
	            }
	        } catch (ConnectTimeoutException e) {
	           
	        } catch (UnsupportedEncodingException e) {
	           ;
	        } catch (IOException e) {
	            
	        } catch (Exception e) {
	            
	        }

	        return result;
	    }
	 
}
